package com.ziroom.finance.rabbitmq.common.interceptor;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import com.ziroom.finance.rabbitmq.common.base.BaseController;
import com.ziroom.finance.rabbitmq.common.base.CommonException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

/**
 * 类说明      :捕获controller异常
 * 作者        :liuys
 * 日期        :2015年12月23日下午4:04:06
 * 版本号      :V1.0
 */
public class ExceptionCatch extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionCatch.class);

    /**
     * 描述     :捕获异常
     *
     * @param pjd       proceedingJoinPoint
     * @return  CommonResponse or ModelAndView
     * @throws Throwable 作者     :liuys
     *                   日期     :2015年12月23日 下午4:05:37
     *                   版本号    :V1.0
     */
    public Object catchControllerException(ProceedingJoinPoint pjd) throws Throwable {
        Object ret = null;
        //接入cat监控远程调用用到的时间
        String className = pjd.getSignature().getDeclaringTypeName();
        String methodName = pjd.getSignature().getName();
        logger.debug("对象:" + className);
        logger.debug("方法:" + methodName);

        try {
            className = className.substring(className.lastIndexOf(".") + 1);
        } catch (Exception e) {
            logger.info("ExceptionCatch类名截取异常: ", e);
        }

        Transaction transaction = Cat.newTransaction("localResponse/" + className, methodName);
        try {
            ret = pjd.proceed();
            //设置成功状态
            transaction.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            if (e instanceof CommonException) {
                transaction.setStatus(e);
                int code = ((CommonException) e).getCode();
                if (((CommonException) e).isFlag()) {
                    return doReturn(ret, code, e.getMessage());
                } else {
                    return doReturn(ret, code, null);
                }
            } else {
                // 未知错误
                Cat.logError(e);
                transaction.setStatus(e);
                logger.error("未知应用级错误", e);
                return doReturn(ret, 200000, e.getMessage());
            }
        } finally {
            //Transaction
            transaction.complete();
        }

        return ret;
    }

    /**
     * do return action
     * @author duxiaokang
     * @param ret       return object
     * @param code      error code
     * @param message   error message
     * @return  object or modelAndView
     */
    private Object doReturn(Object ret, int code, String message) {
        if (ret instanceof ModelAndView) {
            return new ModelAndView("404").addObject("errorMsg", message);
        } else {
            return errorReturn(code, message);
        }
    }
}
